﻿using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using UtilZ.Dotnet.Ex.Base;
using UtilZ.Dotnet.Ex.Communication.Base;
using UtilZ.Dotnet.Ex.Exceptions;

namespace UtilZ.Dotnet.Ex.Communication.Net.Telnet
{
    internal partial class ListenTelnetClient
    {
        #region ITelnetClient
        /// <summary>
        /// 获取或设置消息编码
        /// </summary>
        public Encoding MessageEncoding
        {
            get { return this._messageEncoding; }
            set { this._messageEncoding = value; }
        }

        /// <summary>
        /// 获取Telnet客户端操作系统类型
        /// </summary>
        public OSPlatformID Platform
        {
            get { return _platform; }
            set { _platform = value; }
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="message">消息</param>
        public void SendMessage(string message)
        {
            byte[] data = this._messageEncoding.GetBytes(message);
            this.Send(data);
        }

        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="data">数据</param>
        /// <param name="offset">发送起始位置</param>
        /// <param name="length">数据长度</param>
        public void Send(byte[] data, int offset = -1, int length = -1)
        {
            if (length < 0)
            {
                length = data.Length;
            }

            int sendOffset = offset;
            if (sendOffset < 0)
            {
                sendOffset = 0;
            }

            while (sendOffset < length)
            {
                try
                {
                    sendOffset += this._socket.Send(data, sendOffset, length - sendOffset, SocketFlags.None);
                }
                catch (ObjectDisposedException)
                {
                    break;
                }
                catch (NullReferenceException)
                {
                    throw new ConnectException("未连接到服务端");
                }
                catch (SocketException sex)
                {
                    if (NetHelper.SocketErrorIsDisconnect(sex.SocketErrorCode))
                    {
                        this.OnRaiseDisconnect(DisconnectMode.Passive);
                    }

                    throw;
                }
            }
        }

        /// <summary>
        /// 断开连接命令
        /// </summary>
        public void Disconnect()
        {
            this.OnRaiseDisconnect(DisconnectMode.Active);
        }

        /// <summary>
        /// 清空命令历史
        /// </summary>
        public void ClearCommandHistory()
        {
            this._historyCommandList.Clear();
            this._historyCommandIndex = 0;
            string str = $"{TelnetConstant.END_LINE_CURSOR}clear history command succes{TelnetConstant.END_LINE_CURSOR}";
            this.SendMessage(str);
        }

        /// <summary>
        /// 清空屏幕
        /// </summary>
        /// <param name="lineCount">清空行数</param>
        public void ClearScreen(int lineCount)
        {
            //string clear;
            //if (lineCount > 0)
            //{
            //    clear = $"clear {lineCount}";
            //}
            //else
            //{
            //    clear = "clear";
            //}

            //switch (this._platform)
            //{
            //    case PlatformID.Win32NT:
            //    case PlatformID.Win32S:
            //    case PlatformID.WinCE:
            //        clear = "cls";
            //        break;
            //    case PlatformID.MacOSX:
            //        break;
            //    case PlatformID.Unix:
            //        clear = "clear";
            //        break;
            //    default:
            //        clear = "\033c";
            //        break;
            //}

            //this.SendMessage(clear);

            byte[] buffer = new byte[] { 0x1b, 0x5b, 0x48, 0x1b, 0x5b, 0x4a };
            this.Send(buffer);
            this.SendMessage(TelnetConstant.CURSOR);
        }

        /// <summary>
        /// 设置历史命令缓存大小
        /// </summary>
        /// <param name="capcity"></param>
        public void SetHistoryCommandCapcity(int capcity)
        {
            this._historyCommandCapcity = capcity;
            this.SendMessage(TelnetConstant.END_LINE_CURSOR);
        }


        /// <summary>
        /// 获取Telnet信息
        /// </summary>
        /// <returns></returns>
        public string GetTelnetInfo()
        {
            return $"{TelnetConstant.END_LINE_CURSOR} OS:{this._platform.ToString()} Encoding:\"{this._messageEncoding.BodyName}\" Capcity:{this._historyCommandCapcity} {TelnetConstant.END_LINE_CURSOR}";
        }
        #endregion
    }
}
